package cn.gok.springsecuritydemo02.serivce;

import cn.gok.springsecuritydemo02.entity.User;
import cn.gok.springsecuritydemo02.dao.UserDAO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * @author: chen fan
 * @since: 2022/11/18 11:26
 * @description:
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDAO userDAO;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);

        //先根据用户名查询出用户信息
        User user = userDAO.selectOne(queryWrapper);
        if ( user == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        //封装UserDetails对象返回，可以返回Spring Security 提供的默认用户对象
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                // {noop}表示不进行加密，  {bcrypt}表示采用bcrypt算法进行加密
                "{bcrypt}"+user.getPassword(),
                true,true,true,true,
                new ArrayList<GrantedAuthority>()
        );
    }
}
